package com.sap.sap_mangers.controller;

import com.sap.sap_mangers.Vo.SawbsVo.ManagerForOrderVo;
import com.sap.sap_mangers.Vo.SawbsVo.SawbsMessageVo;
import com.sap.sap_mangers.Vo.UserVo.UserMessage;
import com.sap.sap_mangers.dto.sawbs.Approval;
import com.sap.sap_mangers.dto.sawbs.SawbsMessage;
import com.sap.sap_mangers.dto.sawbs.SawbsTaskSummary;
import com.sap.sap_mangers.dto.sawbs.SawbsTasksSelect;
import com.sap.sap_mangers.email.IMailService;
import com.sap.sap_mangers.pojo.*;
import com.sap.sap_mangers.service.CacheService;
import com.sap.sap_mangers.service.DynamicService;
import com.sap.sap_mangers.service.SawbsService;
import com.sap.sap_mangers.service.UserService;
import com.sap.sap_mangers.until.*;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.*;

/**
 * @author 樊东升
 * @date 2022/7/31 18:46
 * 软件协会每年会有选拔学习小组的活动
 * 这个Controller就是用来处理学习小组相关接口的类
 */
@RestController
@RequestMapping("/Sawbs")
public class SawbsController {
    @Autowired
    private SawbsService sawbsService;

    @Autowired
    private DynamicService dynamicService;

    @Autowired
    private UserService userService;

    @Autowired
    private CacheService cacheService;

    @Autowired
    private IMailService imailService;
    @Autowired
    private CosUntil cosUntil;

    @Autowired
    private RedisCache redisCache;

    /**
     * length用户要求产生字符串的长度
     *
     * @param length 随机字符串的长度
     * @return 随机字符串
     */
    public static String getRandomString(int length) {
        String str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        Random random = new Random();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(62);
            sb.append(str.charAt(number));
        }
        return sb.toString();
    }

    /**
     * 获取学习小组学习信息
     * GET /Sawbs/getSawbsMessage
     * 接口ID：31989149
     * 接口地址：<a href="https://www.apifox.cn/web/project/1216547/apis/api-31989149">...</a>
     * @param year 学年
     * @param order 活动次序
     * @param week 周数
     * @return 视图
     */
    @PreAuthorize("hasAuthority('游客')")
    @GetMapping("/getSawbsMessage")
    public SimpleJson getSawbsMessage(@Param("year") Integer year, @Param("order") Integer order, @Param("week") Integer week) {
        SawbsMessage sawbsMessage = new SawbsMessage();
        sawbsMessage.setYear(year);
        sawbsMessage.setOrder(order);
        sawbsMessage.setWeek(week);
        return new SimpleJson(1, "获取成功", sawbsService.getSawbsMessage(sawbsMessage));
    }

    /**
     * 协会部长申请成为当前活动负责人，这里不需要传入信息，信息全部由其他表的内容获得
     *
     * @return 申请是否成功(只是接口运行是否成功)
     */
    @PreAuthorize("hasAuthority('旧管理员')")
    @PostMapping("/applyToBeStudyGroupLeader")
    public SimpleJson applyToBeStudyGroupLeader() {
        return sawbsService.applyToBeStudyGroupLeader();
    }

    /**
     * 获取待审批成员信息(负责人申请信息)
     * GET /Sawbs/getApprovalMessage
     * 接口ID：32608931
     * 接口地址：<a href="https://www.apifox.cn/web/project/1216547/apis/api-32608931">...</a>
     * @return 获取待审批成员信息(负责人申请信息)
     */
    @PreAuthorize("hasAuthority('会长')")
    @GetMapping("/getApprovalMessage")
    public SimpleJson getApprovalMessage() {
        return sawbsService.getApprovalMessage();
    }

    /**
     * 一次审批一个人
     *
     * @param approval 被审批人的学号
     * @return 是否审批成功
     */
    @PreAuthorize("hasAuthority('会长')")
    @PostMapping("/responsibleForApproval")
    public SimpleJson responsibleForApproval(@RequestBody Approval approval) {
        try {
            sawbsService.responsibleForApproval(approval.getUsername());
        } catch (Exception e) {
            return new SimpleJson(1, "审批失败，服务器错误！");
        }
        return new SimpleJson(0, "审批成功");
    }

    /**
     * 一次审批一批人
     *
     * @param approval 一批人的学号
     * @return 是否审批成功
     */
    @PreAuthorize("hasAuthority('会长')")
    @PostMapping("/responsibleForApprovalList")
    public SimpleJson responsibleForApprovalList(@RequestBody Approval approval) {
        try {
            for (String username : approval.getUsernames()) {
                sawbsService.responsibleForApproval(username);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new SimpleJson(1, "出现错误，审批失败，请联系会长");
        }
        return new SimpleJson(0, "批量审批成功");
    }

    /**
     * 创建活动
     * 1.修改动态表
     * 2.在活动表中添加活动
     *
     * @param activity 活动信息
     * @return WeatherUtil
     */
    @PreAuthorize("hasAuthority('会长')")
    @PostMapping("/createActivity")
    public SimpleJson createActivity(@RequestBody Activity activity) {
        //根据动态表设置年份
        activity.setSawbsActivityYear(Integer.parseInt(dynamicService.getYear()));
        //活动次数+1,周数置为 1
//        dynamicService.changeOrder();
        //2022/9/4记录 white修改 - 这里不做周数加一，我们规定只有在创建周任务的时候才周数加一(有待商榷)

        dynamicService.changeOrder();//周数置为0

        //根据动态表设置第几次活动
        activity.setSawbsActivityOrder(Integer.parseInt(dynamicService.getOrder()));
        sawbsService.createActivity(activity);
        return new SimpleJson(0, "活动创建成功");
    }

    /**
     * 获取该负责人的被负责人信息
     *
     * @return 被负责人的信息
     */
    @PreAuthorize("hasAuthority('旧管理员')")
    @GetMapping("/getManagerUsers")
    public SimpleJson getManagerUsers() {
        return sawbsService.getManagerUsers();
    }

    /**
     * 成员退出软协小队
     *
     * @return 成功
     */
    @PreAuthorize("hasAuthority('正式成员')")
    @PostMapping("/memberExit")
    public SimpleJson memberExit() {
        sawbsService.memberExit();
        return SimpleJson.SUCCESS;
    }

    /**
     * 负责人退出软协小队管理
     *
     * @return 成功
     */
    @PreAuthorize("hasAuthority('正式成员')")
    @PostMapping("/managerExit")
    public SimpleJson managerExit() {
        sawbsService.managerExit();
        return SimpleJson.SUCCESS;
    }

    /**
     * 将学习小组每周的学习情况写入
     *
     * @param sawbsMessageVo 学习情况
     * @return 学习情况信息
     */
    @PreAuthorize("hasAuthority('旧管理员')")
    @PostMapping("/writeOrUpdateSawbsMessageVo")
    public SimpleJson writeOrUpdateSawbsMessageVo(@RequestBody SawbsMessageVo sawbsMessageVo) {
        //判断score表中是否有信息
        if (!sawbsService.existUserScoreInSawbsScoreTable(sawbsMessageVo)) {
            if (sawbsMessageVo.identityInformation()) {
                return new SimpleJson(1, "分数范围应为[1,5]的整数");
            }
            return sawbsService.writeSawbsMessageVo(sawbsMessageVo);
        } else {
            try {
                return sawbsService.updateSawbsMessageVo(sawbsMessageVo);
            } catch (Exception e) {
                return new SimpleJson(1, "修改-异常操作!");
            }
        }
    }

    /**
     * 获取本周学习任务
     *
     * @return 本周学习任务
     */
    @PreAuthorize("hasAuthority('正式成员')")
    @GetMapping("/getTaskThisWeek")
    public SimpleJson getTaskThisWeek() {
        SapSawbsTask taskThisWeek = sawbsService.getTaskThisWeek();
        if (taskThisWeek == null) {
            return new SimpleJson(1, "本周暂未发布学习任务");
        }
        return new SimpleJson(0, "获取本周学习任务成功", taskThisWeek);
    }

    /**
     * 获取本次活动每周的学习任务(集合)
     *
     * @return 本次活动每周的学习任务集合
     */
    @PreAuthorize("hasAuthority('正式成员')")
    @GetMapping("/getTaskThisOrder")
    public SimpleJson getTaskThisOrder() {
        List<SapSawbsTask> taskThisOrder = sawbsService.getTaskThisOrder();
        if (taskThisOrder.isEmpty()) {
            return new SimpleJson(1, "本次活动暂未发布学习任务");
        }
        return new SimpleJson(0, "获取本次活动每周的学习任务集合成功", taskThisOrder);
    }

    /**
     * 获取指定活动每周的学习任务(集合)
     *
     * @return 指定活动每周的学习任务集合
     */
    @PreAuthorize("hasAuthority('正式成员')")
    @GetMapping("/getTaskByCondition")
    public SimpleJson getTaskByCondition(@Param("year") Integer year, @Param("order") Integer order) {
        SawbsTasksSelect select = new SawbsTasksSelect(year, order);
        if (select.getYear() == null || select.getOrder() == null) {
            return new SimpleJson(2, "请输入参数");
        }
        List<SapSawbsTask> taskByCondition = sawbsService.getTaskByCondition(select.getYear(), select.getOrder());
        if (taskByCondition.isEmpty()) {
            return new SimpleJson(1, "未查找到相关信息");
        }
        return new SimpleJson(0, "获取指定活动每周的学习任务成功", taskByCondition);
    }

    /**
     * 获取当前的软协小队活动详细信息
     *
     * @return 当前的软协小队活动详细信息
     */
    @PreAuthorize("hasAuthority('正式成员')")
    @GetMapping("/getThisSawbsActivity")
    public SimpleJson getThisSawbsActivity() {
        SapSawbsActivity thisSawbsActivity = sawbsService.getThisSawbsActivity();
        return new SimpleJson(0, "获取当前的软协小队活动详细信息成功", thisSawbsActivity);
    }

    /**
     * 查询指定小队活动的详细信息
     *
     * @return 指定小队活动的详细信息
     */
    @PreAuthorize("hasAuthority('正式成员')")
    @GetMapping("/getSawbsActivityByCondition")
    public SimpleJson getSawbsActivityByCondition(@Param("year") Integer year, @Param("order") Integer order) {
        SawbsTasksSelect select = new SawbsTasksSelect(year, order);
        if (select.getYear() == null || select.getOrder() == null) {
            return new SimpleJson(1, "请输入参数");
        }
        SapSawbsActivity sawbsActivityByCondition = sawbsService.getSawbsActivityByCondition(select.getYear(), select.getOrder());
        if (sawbsActivityByCondition == null) {
            return new SimpleJson(0, "没能找到指定的软协小队活动");
        }
        return new SimpleJson(0, "获取指定软协小队活动详细信息成功", sawbsActivityByCondition);
    }

    /**
     * 获取所有小队活动的详细信息 (按活动的时间(年份和次数)从近到远排序 年份从大到小，次数从大到小)
     *
     * @return 所有小队活动的详细信息集合 (按活动的时间(年份和次数)从近到远排序)
     */
    @PreAuthorize("hasAuthority('正式成员')")
    @GetMapping("/getAllSawbsActivities")
    public SimpleJson getAllSawbsActivities() {
        List<SapSawbsActivity> allSawbsActivities = sawbsService.getAllSawbsActivities();
        return new SimpleJson(0, "获取指定软协小队活动详细信息成功", allSawbsActivities);
    }

    @PreAuthorize("hasAuthority('旧管理员')")
    @PostMapping("/addTaskForWeek")
    public SimpleJson addTaskForWeek(@RequestParam("context") String context,
                                     @RequestParam("theme") String theme,
                                     @RequestParam("image") MultipartFile image,
                                     @RequestParam("file") MultipartFile file) {
        //消息合理性判断
        if (!StringUtils.hasText(context) || !StringUtils.hasText(theme) ||
                image == null || file == null || image.isEmpty() || file.isEmpty()) {
            return new SimpleJson(1, "您有信息为null！");
        }

        if (context.length() > 8192) {
            return new SimpleJson(6, "每周任务的内容字数超出限制!");
        }
        if (theme.length() > 32) {
            return new SimpleJson(6, "每周任务的标题超出字数限制!");
        }

        if (!Objects.requireNonNull(file.getOriginalFilename()).endsWith(".md")) {
            return new SimpleJson(2, "格式错误，修改为.md文件格式");
        }
        if (!Objects.requireNonNull(image.getOriginalFilename()).endsWith(".jpg") && !image.getOriginalFilename().endsWith(".png")) {
            return new SimpleJson(2, "格式错误，图片格式应为 .jpg 或 .png");
        }
        String fileName = file.getOriginalFilename();
        String imageName = image.getOriginalFilename();

        try {
            return sawbsService.addTaskForWeek(file, image, theme, context, fileName, imageName);
        } catch (Exception e) {
            return new SimpleJson(5, "错误信息：" + e.getMessage());
        }
    }

    @PreAuthorize("hasAuthority('游客')")
    @GetMapping("/getSawbsYear")
    public SimpleJson getSawbsYear() {
        return new SimpleJson(0, "获取成功", dynamicService.getYear());
    }

    @PreAuthorize("hasAuthority('游客')")
    @GetMapping("/getSawbsOrder")
    public SimpleJson getSawbsOrder() {
        return new SimpleJson(0, "获取成功", dynamicService.getOrder());
    }

    @PreAuthorize("hasAuthority('游客')")
    @GetMapping("/getSawbsWeek")
    public SimpleJson getSawbsWeek() {
        return new SimpleJson(0, "获取成功", dynamicService.getWeek());
    }

    /**
     * 随机生成每周的负责人匹配关系
     *
     * @return 是否成功
     */
    @PreAuthorize("hasAuthority('会长')")
    @PostMapping("/createWeeklyManagerMatchingRelationship")
    public SimpleJson createWeeklyManagerMatchingRelationship() {
        //事务处理
        int result;
        try {
            result = sawbsService.createWeeklyManagerMatchingRelationship();
        } catch (Exception e) {
            return SimpleJson.FAILURE;
        }
        if (result == 0) {
            return SimpleJson.SUCCESS;
        } else if (result == 1) {
            return new SimpleJson(1, "已经有小组成员上交了作业，本周将无法随机负责人(如果有新加入软协小组的成员则本周可以使用该功能)");
        } else if (result == 2) {
            return new SimpleJson(0, "有新的成员加入，所以本次仅给新的成员分配了负责人，可以继续使用该功能给全部成员随机负责人");
        } else {
            return new SimpleJson(1, "出现未知错误，请联系会长");
        }
    }

    @PreAuthorize("hasAuthority('正式成员')")
    @GetMapping("/summary/getSummaryMessageByYear")
    public SimpleJson getSummaryMessageByYear(@RequestParam("year") String year) {
        return sawbsService.getSummaryMessageByYear(year);
    }

    @PreAuthorize("hasAuthority('正式成员')")
    @GetMapping("/summary/getSummaryMessageByOrder")
    public SimpleJson getSummaryMessageByOrder(@RequestParam("year") String year, @RequestParam("order") String order) {
        return sawbsService.getSummaryMessageByOrder(year, order);
    }

    @PreAuthorize("hasAuthority('正式成员')")
    @GetMapping("/summary/getSummaryMessageByWeek")
    public SimpleJson getSummaryMessageByWeek(@RequestParam("year") String year, @RequestParam("order") String order, @RequestParam("week") String week) {
        System.out.println(year + "-" + order + "-" + week);
        return sawbsService.getSummaryMessageByWeek(year, order, week);
    }


    @PreAuthorize("hasAuthority('正式成员')")
    @GetMapping("/summary/getSummaryMessageOfYear")
    public SimpleJson getSummaryMessageOfYear(@RequestParam("year") String year) {
        return sawbsService.getSummaryMessageOfYear(year);
    }


    @PreAuthorize("hasAuthority('正式成员')")
    @GetMapping("/summary/getSummaryMessage")
    public SimpleJson getSummaryMessageOfOrder(@RequestParam("year") String year, @RequestParam("order") String order) {
        return sawbsService.getSummaryMessageOfOrder(year, order);
    }

    @PreAuthorize("hasAuthority('正式成员')")
    @GetMapping("/summary/getSummaryMessageByDynamic")
    public SimpleJson getSummaryMessageByDynamic() {
        return sawbsService.getSummaryMessageByDynamic();
    }

    /**
     * 添加总结信息表
     *
     * @param httpRequest http
     * @return 视图
     */
    @PreAuthorize("hasAuthority('旧管理员')")
    @PostMapping("/summary/addSummaryMessage")
    public SimpleJson addSummaryMessage(HttpServletRequest httpRequest) {
        MultipartHttpServletRequest params = ((MultipartHttpServletRequest) httpRequest);
        List<MultipartFile> files = ((MultipartHttpServletRequest) httpRequest).getFiles("images");
        String context = params.getParameter("context");
        String topic = params.getParameter("topic");
        int ignoreWeek = 0;
        int ignoreOrder = 0;
        try {
            ignoreWeek = Integer.parseInt(params.getParameter("ignoreWeek"));
            ignoreOrder = Integer.parseInt(params.getParameter("ignoreOrder"));
            if (ignoreOrder == 0 && ignoreWeek == 0) {
                SimpleJson summaryMessageByWeek = sawbsService.getSummaryMessageByWeek(dynamicService.getYear(), dynamicService.getOrder(), dynamicService.getWeek());
                System.out.println("---" + summaryMessageByWeek.getData());
                if (summaryMessageByWeek.getData() != null) {
                    return getSimpleJson(files, context, topic, 0, 0, true);
                } else {
                    return getSimpleJson(files, context, topic, 0, 0, false);
                }
            } else if (ignoreOrder == 1 && ignoreWeek == 0) {
                SimpleJson summaryMessageOfYear = sawbsService.getSummaryMessageOfYear(dynamicService.getYear());
                if (summaryMessageOfYear.getData() != null) {
                    return getSimpleJson(files, context, topic, 0, 1, true);
                } else {
                    return getSimpleJson(files, context, topic, 0, 1, false);
                }
            } else if (ignoreOrder == 0 && ignoreWeek == 1) {
                SimpleJson summaryMessageOfOrder = sawbsService.getSummaryMessageOfOrder(dynamicService.getYear(), dynamicService.getOrder());
                if (summaryMessageOfOrder.getData() != null) {
                    return getSimpleJson(files, context, topic, 1, 0, true);
                } else {
                    return getSimpleJson(files, context, topic, 1, 0, false);
                }
            }
        } catch (Exception e) {
            return new SimpleJson(1, "ignoreWeek和ignoreOrder字段必须是数字(字符串格式的数字也可以)");
        }
        return SimpleJson.SUCCESS;
    }

    /**
     * 添加总结函数抽取
     * @param files 文件
     * @param context 内容
     * @param topic 标题
     * @param ignoreWeek 是否是活动总结
     * @param ignoreOrder 是否是学年总结
     * @param isUpdate 是否修改过
     * @return 视图
     */
    private SimpleJson getSimpleJson(List<MultipartFile> files, String context, String topic, int ignoreWeek, int ignoreOrder, Boolean isUpdate) {
        SawbsTaskSummary sawbsTaskSummary = new SawbsTaskSummary();
        sawbsTaskSummary.setYear(Integer.parseInt(dynamicService.getYear()));
        sawbsTaskSummary.setOrder(Integer.parseInt(dynamicService.getOrder()));
        sawbsTaskSummary.setWeek(Integer.parseInt(dynamicService.getWeek()));
        sawbsTaskSummary.setTopic(topic);
        sawbsTaskSummary.setContext(context);
        sawbsTaskSummary.setIgnoreOrder(ignoreOrder);
        sawbsTaskSummary.setIgnoreWeek(ignoreWeek);
        sawbsTaskSummary.setUsername(JwtUtil.getUserForToken());
        UserMessage userMessage = userService.getUserMessage(JwtUtil.getUserForToken());
        sawbsTaskSummary.setName(userMessage.getRealName());
        sawbsTaskSummary.setCreateTime(new Timestamp(System.currentTimeMillis()));
        sawbsTaskSummary.setImageNum(files.size());
        SnowflakeIdWorker idWorker = new SnowflakeIdWorker(0, 0);
        String imageId = String.valueOf(idWorker.nextId());
        sawbsTaskSummary.setImageId(imageId);
        List<String> imageList = new ArrayList<>();
        for (MultipartFile file : files) {
            String cosKey = "taskSummaryImage/" + file.getOriginalFilename();
            try {
                String cosUrl = cosUntil.getCosUrl(file, cosKey);
                imageList.add(cosUrl);
            } catch (IOException e) {
                e.printStackTrace();
                return new SimpleJson(2, "图片上传对象储存出错!");
            }
        }
        if (!isUpdate) {
            return sawbsService.addSummaryMessage(sawbsTaskSummary, imageList);
        } else {
            return sawbsService.updateTaskSummaryMessage(sawbsTaskSummary, imageList);
        }
    }

    @PreAuthorize("hasAuthority('游客')")
    @GetMapping("/getNowTime")
    public SimpleJson getNowTime() {
        Map<String, String> map = new HashMap<>(3);
        String year = dynamicService.getYear();
        String order = dynamicService.getOrder();
        String week = dynamicService.getWeek();
        map.put("year", year);
        map.put("order", order);
        map.put("week", week);
        return new SimpleJson(0, map);
    }

    @PreAuthorize("hasAuthority('正式成员')")
    @GetMapping("/getScoreForView")
    public SimpleJson getScoreForView(@RequestParam("order") Integer order) {
        return sawbsService.getScoreForView(order);
    }

    /**
     * 获取当前周的分数信息
     *
     * @return ..
     */
    @PreAuthorize("hasAuthority('正式成员')")
    @Deprecated
    @GetMapping("/getScoreForWeek")
    public SimpleJson getScoreForWeek() {
        DynamicMessage dynamicMessage = new DynamicMessage(Integer.valueOf(dynamicService.getYear()), Integer.valueOf(dynamicService.getOrder()), Integer.valueOf(dynamicService.getWeek()));
        return new SimpleJson(sawbsService.getScoreForWeek(dynamicMessage));
    }

    /**
     * 获取任意周的分数信息(传入<0的值则代表获取最近内容)
     *
     * @return ..
     */
    @PreAuthorize("hasAuthority('正式成员')")
    @GetMapping("/getScoreForAnyWeek")
    public SimpleJson getScoreForAnyWeek(@RequestParam("week") Integer week) {
        if (week < 0) {
            DynamicMessage dynamicMessage = new DynamicMessage(Integer.valueOf(dynamicService.getYear()), Integer.valueOf(dynamicService.getOrder()), Integer.valueOf(dynamicService.getWeek()));
            return new SimpleJson(sawbsService.getScoreForWeek(dynamicMessage));
        }
        DynamicMessage dynamicMessage = new DynamicMessage(Integer.valueOf(dynamicService.getYear()), Integer.valueOf(dynamicService.getOrder()), week);
        return new SimpleJson(sawbsService.getScoreForWeek(dynamicMessage));
    }

    /**
     * 获取这次活动所有周数的总分数
     *
     * @return --
     */
    @PreAuthorize("hasAuthority('正式成员')")
    @Deprecated
    @GetMapping("/getScoreForOrder")
    public SimpleJson getScoreForOrder() {
        return new SimpleJson(sawbsService.getScoreForOrder(-1));
    }

    /**
     * 获取当前学年任意一次活动的所有周的总分数(传入<0的值则代表获取最近内容)
     *
     * @param order 活动次序
     * @return --
     */
    @PreAuthorize("hasAuthority('正式成员')")
    @GetMapping("/getScoreForAnyOrder")
    public SimpleJson getScoreForAnyOrder(@RequestParam("order") Integer order) {
        if (order < 0) {
            return new SimpleJson(sawbsService.getScoreForOrder(-1));
        }
        return new SimpleJson(sawbsService.getScoreForOrder(order));
    }

    @PreAuthorize("hasAuthority('正式成员')")
    @Deprecated
    @GetMapping("/getScoreForYear")
    public SimpleJson getScoreForYear() {
        return new SimpleJson(sawbsService.getScoreForAnyYear(-1));
    }

    /**
     * 获取任意学年总分(传入<0的值则代表获取最近内容)
     *
     * @param year 年
     * @return ..
     */
    @PreAuthorize("hasAuthority('正式成员')")
    @GetMapping("/getScoreForAnyYear")
    public SimpleJson getScoreForAnyYear(@RequestParam("year") Integer year) {
        if (year < 0) {
            return new SimpleJson(sawbsService.getScoreForAnyYear(-1));
        }
        return new SimpleJson(sawbsService.getScoreForAnyYear(year));
    }


    /**
     * 获取个人任意学年任意活动的任何一周的分数
     *
     * @return
     */
    @PreAuthorize("hasAuthority('正式成员')")
    @GetMapping("/getOtherYearAnyWeekScoreForUser")
    public SimpleJson getOtherYearAnyWeekScoreForUser(@RequestParam("year") Integer year, @RequestParam("order") Integer order, @RequestParam("week") Integer week) {
        if (year < 0) {
            if (order < 0) {
                if (week < 0) {
                    return new SimpleJson(sawbsService.getScoreForUser(
                            new DynamicMessage(
                                    dynamicService.getYearForInt(),
                                    dynamicService.getOrderForInt(),
                                    dynamicService.getWeekForInt(),
                                    JwtUtil.getUserForToken())));
                } else {
                    return new SimpleJson(sawbsService.getScoreForUser(
                            new DynamicMessage(
                                    dynamicService.getYearForInt(),
                                    dynamicService.getOrderForInt(),
                                    week,
                                    JwtUtil.getUserForToken())));
                }
            } else {
                if (week < 0) {
                    return new SimpleJson(1, "消息获取错误，不能在order大于0的情况下，week小于0");
                } else {
                    return new SimpleJson(sawbsService.getScoreForUser(
                            new DynamicMessage(
                                    dynamicService.getYearForInt(),
                                    order,
                                    week,
                                    JwtUtil.getUserForToken())));
                }
            }
        } else {
            if (order < 0) {
                return new SimpleJson(1, "消息获取错误，不能在year小于0的情况下，order小于0");
            } else {
                if (week < 0) {
                    return new SimpleJson(1, "消息获取错误，不能在order大于0的情况下，week小于0");
                } else {
                    return new SimpleJson(sawbsService.getScoreForUser(
                            new DynamicMessage(
                                    year,
                                    order,
                                    week,
                                    JwtUtil.getUserForToken())));
                }
            }
        }
    }


    /**
     * 获取个人用户任意学年任意活动分数(每周)
     *
     * @return
     */
    @PreAuthorize("hasAuthority('正式成员')")
    @GetMapping("/getYearAnyOrderScoreForUser")
    public SimpleJson getYearAnyOrderScoreForUser(@RequestParam("year") Integer year, @RequestParam("order") Integer order) {
        if (year < 0) {
            if (order < 0) {
                return new SimpleJson(sawbsService.getScoreForUserOrder(
                        new DynamicMessage(
                                dynamicService.getYearForInt(),
                                dynamicService.getOrderForInt(),
                                null,
                                JwtUtil.getUserForToken())));
            } else {
                return new SimpleJson(sawbsService.getScoreForUserOrder(
                        new DynamicMessage(
                                dynamicService.getYearForInt(),
                                order,
                                null,
                                JwtUtil.getUserForToken())));
            }
        } else {
            if (order < 0) {
                return new SimpleJson(1, "消息获取错误，不能在year大于0的情况下，order小于0");
            } else {
                return new SimpleJson(sawbsService.getScoreForUserOrder(
                        new DynamicMessage(
                                year,
                                order,
                                null,
                                JwtUtil.getUserForToken())));
            }
        }
    }

    /**
     * 获取个人用户任意学年分数(每周)
     *
     * @param year 年份呢
     * @return ..
     */
    @PreAuthorize("hasAuthority('正式成员')")
    @GetMapping("/getYearScoreForUser")
    public SimpleJson getYearScoreForUser(@RequestParam("year") Integer year) {
        if (year < 0) {
            return new SimpleJson(sawbsService.getScoreForUserYear(
                    new DynamicMessage(
                            dynamicService.getYearForInt(),
                            null,
                            null,
                            JwtUtil.getUserForToken())));
        } else {
            return new SimpleJson(sawbsService.getScoreForUserYear(
                    new DynamicMessage(
                            year,
                            null,
                            null,
                            JwtUtil.getUserForToken())));
        }
    }

    @PreAuthorize("hasAuthority('正式成员')")
    @GetMapping("/getSumYearAnyOrderScoreForUser")
    public SimpleJson getYearScoreForUser(@RequestParam("year") Integer year, @RequestParam("order") Integer order) {
        if (year < 0) {
            SapSawbsScore scoreSumForUser;
            if (order < 0) {
                scoreSumForUser = sawbsService.getScoreSumForUser(dynamicService.getYearForInt(), dynamicService.getOrderForInt(), JwtUtil.getUserForToken());
            } else {
                scoreSumForUser = sawbsService.getScoreSumForUser(dynamicService.getYearForInt(), order, JwtUtil.getUserForToken());
            }
            scoreSumForUser.setSumOfSawbsScore(scoreSumForUser.getSawbsScoreNote() + scoreSumForUser.getSawbsScoreSummary() + scoreSumForUser.getSawbsScoreDepth() + scoreSumForUser.getSawbsScoreEnthusiasm() + scoreSumForUser.getSawbsScoreComprehensive());
            return new SimpleJson(scoreSumForUser);
        } else {
            SapSawbsScore scoreSumForUser;
            if (order < 0) {
                return new SimpleJson(1, "消息获取错误，不能在year大于0的情况下，order小于0");
            } else {
                scoreSumForUser = sawbsService.getScoreSumForUser(year, order, JwtUtil.getUserForToken());
            }
            scoreSumForUser.setSumOfSawbsScore(scoreSumForUser.getSawbsScoreNote() + scoreSumForUser.getSawbsScoreSummary() + scoreSumForUser.getSawbsScoreDepth() + scoreSumForUser.getSawbsScoreEnthusiasm() + scoreSumForUser.getSawbsScoreComprehensive());
            return new SimpleJson(scoreSumForUser);
        }
    }

    @PreAuthorize("hasAuthority('正式成员')")
    @GetMapping("/getSumYearAndScoreForUser")
    public SimpleJson getSumYearAndScoreForUser(@RequestParam("year") Integer year) {
        List<SapSawbsScore> scoreSumForUser;
        if (year < 0) {
            scoreSumForUser = sawbsService.getSumYearAndScoreForUser(dynamicService.getYearForInt(), JwtUtil.getUserForToken());
        } else {
            scoreSumForUser = sawbsService.getSumYearAndScoreForUser(year, JwtUtil.getUserForToken());
        }
        return new SimpleJson(scoreSumForUser);
    }

    @PreAuthorize("hasAuthority('正式成员')")
    @GetMapping("/getSumYearScoreForUser")
    public SimpleJson getSumYearScoreForUser(@RequestParam("year") Integer year) {
        SapSawbsScore scoreSumForUser;
        if (year < 0) {
            scoreSumForUser = sawbsService.getScoreSumForUserYear(dynamicService.getYearForInt(), JwtUtil.getUserForToken());
        } else {
            scoreSumForUser = sawbsService.getScoreSumForUserYear(year, JwtUtil.getUserForToken());
        }
        return new SimpleJson(scoreSumForUser);
    }

    /**
     * 获取当前用户任意周负责人的详情
     *
     * @param year  学年
     * @param order 活动次序
     * @param week  周数
     * @return ..
     */
    @PreAuthorize("hasAuthority('正式成员')")
    @GetMapping("/getUserManagerForWeek")
    public SimpleJson getUserManagerForWeek(@RequestParam("year") Integer year, @RequestParam("order") Integer order, @RequestParam("week") Integer week) {
        if (year < 0) {
            if (order < 0) {
                if (week < 0) {
                    return sawbsService.getUserManagerForWeek(new DynamicMessage(
                            dynamicService.getYearForInt(),
                            dynamicService.getOrderForInt(),
                            dynamicService.getWeekForInt(),
                            JwtUtil.getUserForToken()
                    ));
                } else {
                    return sawbsService.getUserManagerForWeek(new DynamicMessage(
                            dynamicService.getYearForInt(),
                            dynamicService.getOrderForInt(),
                            week,
                            JwtUtil.getUserForToken()
                    ));
                }
            } else {
                if (week < 0) {
                    return new SimpleJson(1, "消息获取错误，不能在order大于0的情况下，week小于0");
                } else {
                    return sawbsService.getUserManagerForWeek(
                            new DynamicMessage(
                                    dynamicService.getYearForInt(),
                                    order,
                                    week,
                                    JwtUtil.getUserForToken()));
                }
            }
        } else {
            if (order < 0) {
                return new SimpleJson(1, "消息获取错误，不能在year大于0的情况下，order小于0");
            } else {
                if (week < 0) {
                    return new SimpleJson(1, "消息获取错误，不能在order大于0的情况下，week小于0");
                } else {
                    return sawbsService.getUserManagerForWeek(
                            new DynamicMessage(
                                    year,
                                    order,
                                    week,
                                    JwtUtil.getUserForToken()));
                }
            }
        }
    }

    @PreAuthorize("hasAuthority('正式成员')")
    @GetMapping("/getUserManagerForOrder")
    public SimpleJson getUserManagerForOrder(@RequestParam("year") Integer year, @RequestParam("order") Integer order) {
        if (year < 0) {
            if (order < 0) {
                return new SimpleJson(sawbsService.getUserManagerForOrder(new DynamicMessage(dynamicService.getYearForInt(), dynamicService.getOrderForInt(), null, JwtUtil.getUserForToken())));
            } else {
                return new SimpleJson(sawbsService.getUserManagerForOrder(new DynamicMessage(dynamicService.getYearForInt(), order, null, JwtUtil.getUserForToken())));
            }
        } else {
            if (order < 0) {
                return new SimpleJson(1, "消息获取错误，不能在year大于0的情况下，order小于0");
            } else {
                return new SimpleJson(sawbsService.getUserManagerForOrder(new DynamicMessage(year, order, null, JwtUtil.getUserForToken())));
            }
        }

    }

    @PreAuthorize("hasAuthority('正式成员')")
    @GetMapping("/getUserManagerForYear")
    public SimpleJson getUserManagerForYear(@RequestParam("year") Integer year) {

        if (year < 0) {
            return new SimpleJson(sawbsService.getUserManagerForYear(new DynamicMessage(dynamicService.getYearForInt(), null, null, JwtUtil.getUserForToken())));
        } else {
            return new SimpleJson(sawbsService.getUserManagerForYear(new DynamicMessage(year, null, null, JwtUtil.getUserForToken())));
        }
    }


    @PreAuthorize("hasAuthority('正式成员')")
    @GetMapping("/getUserForManager")
    public SimpleJson getUserForManager() {
        return new SimpleJson(sawbsService.getUserForManager());
    }

    @PreAuthorize("hasAuthority('正式成员')")
    @GetMapping("/getUserManagerOrderForLast")
    public SimpleJson getUserManagerOrderForLast() {
        SapSawbsScore sapSawbsScoreByUserLastOrder = sawbsService.getSapSawbsScoreByUserLastOrder("20212676");
        ManagerForOrderVo userManagerForOrder = sawbsService.getUserManagerForOrder(new DynamicMessage((int) sapSawbsScoreByUserLastOrder.getSawbsScoreYear(), (int) sapSawbsScoreByUserLastOrder.getSawbsScoreOrder(), null, JwtUtil.getUserForToken()));
        return new SimpleJson(userManagerForOrder);
    }

    @PreAuthorize("hasAuthority('正式成员')")
    @GetMapping("/getSawbsActivityRecordOfYearOrderWeek")
    public SimpleJson getSawbsActivityRecordOfYearOrderWeek(@RequestParam(required = false) Integer year,
                                                            @RequestParam(required = false) Integer order) {
        return sawbsService.getSawbsActivityRecordOfYearOrderWeek(year, order);
    }


    @PreAuthorize("hasAuthority('正式成员')")
    @GetMapping("/getManagerForUserWeek")
    public SimpleJson getManagerForUserWeek(@RequestParam("year") Integer year, @RequestParam("order") Integer order, @RequestParam("week") Integer week) {

        if (year < 0) {
            if (order < 0) {
                if (week < 0) {
                    return sawbsService.getManagerForUserWeek(new DynamicMessage(
                            dynamicService.getYearForInt(),
                            dynamicService.getOrderForInt(),
                            dynamicService.getWeekForInt(),
                            JwtUtil.getUserForToken()
                    ));
                } else {
                    return sawbsService.getManagerForUserWeek(new DynamicMessage(
                            dynamicService.getYearForInt(),
                            dynamicService.getOrderForInt(),
                            week,
                            JwtUtil.getUserForToken()
                    ));
                }
            } else {
                if (week < 0) {
                    return new SimpleJson(1, "消息获取错误，不能在order大于的情况下，week小于0");
                } else {
                    return sawbsService.getManagerForUserWeek(
                            new DynamicMessage(
                                    dynamicService.getYearForInt(),
                                    order,
                                    week,
                                    JwtUtil.getUserForToken()));
                }
            }
        } else {
            if (order < 0) {
                return new SimpleJson(1, "消息获取错误，不能在year大于0的情况下，order小于0");
            } else {
                if (week < 0) {
                    return new SimpleJson(1, "消息获取错误，不能在order大于0的情况下，week小于0");
                } else {
                    return sawbsService.getManagerForUserWeek(
                            new DynamicMessage(
                                    year,
                                    order,
                                    week,
                                    JwtUtil.getUserForToken()));
                }
            }
        }

    }

    @PreAuthorize("hasAuthority('正式成员')")
    @GetMapping("/getManagerForUserOrder")
    public SimpleJson getManagerForUserOrder(@RequestParam("year") Integer year, @RequestParam("order") Integer order) {

        if (year < 0) {
            if (order < 0) {
                return sawbsService.getManagerForUserOrder(new DynamicMessage(
                        dynamicService.getYearForInt(),
                        dynamicService.getOrderForInt(),
                        null,
                        JwtUtil.getUserForToken()));
            } else {
                return sawbsService.getManagerForUserOrder(new DynamicMessage(
                        dynamicService.getYearForInt(),
                        order,
                        null,
                        JwtUtil.getUserForToken()));
            }
        } else {
            if (order < 0) {
                return new SimpleJson(1, "消息获取错误，不能在order大于的情况下，week小于0");
            } else {
                return sawbsService.getManagerForUserOrder(new DynamicMessage(
                        year,
                        order,
                        null,
                        JwtUtil.getUserForToken()));
            }
        }
    }

    @PreAuthorize("hasAuthority('正式成员')")
    @GetMapping("/getManagerForUserYear")
    public SimpleJson getManagerForUserYear(@RequestParam("year") Integer year) {
        if (year < 0) {
            return sawbsService.getManagerForUserYear(new DynamicMessage(
                    dynamicService.getYearForInt(),
                    null,
                    null,
                    JwtUtil.getUserForToken()
            ));
        } else {
            return sawbsService.getManagerForUserYear(new DynamicMessage(
                    year,
                    null,
                    null,
                    JwtUtil.getUserForToken()
            ));
        }

    }

    @PreAuthorize("hasAuthority('正式成员')")
    @GetMapping("/getManagerForUser")
    public SimpleJson getManagerForUser() {
        return sawbsService.getManagerForUser();
    }


    /**
     * 正式成员申请加入软协学习小组
     */
    @PreAuthorize("hasAuthority('正式成员')")
    @PostMapping("/applySapStudy")
    public SimpleJson applySapStudy() {
        UserMessage userMessage = userService.getUserMessage(JwtUtil.getUserForToken());
        if (userMessage.getRole() != 11) {
            return new SimpleJson(1, "只有软件协会成员才能加入学习小组，部长或者游客均不可以加入");
        }
        return sawbsService.applySapStudy(new DynamicMessage(dynamicService.getYearForInt(), dynamicService.getOrderForInt(), null, JwtUtil.getUserForToken()));
    }

    @PreAuthorize("hasAuthority('游客')")
    @GetMapping("/isJoinSapStudy")
    public SimpleJson isJoinSapStudy() {
        return sawbsService.isJoinSapStudy(new DynamicMessage(dynamicService.getYearForInt(), dynamicService.getOrderForInt(), null, JwtUtil.getUserForToken()));
    }

    @PreAuthorize("hasAuthority('正式成员')")
    @GetMapping("/sendQuitCode")
    public SimpleJson sendQuitCode() {
        Map<String, Object> cacheMap = null;
        try {
            SimpleJson joinSapStudy = isJoinSapStudy();
            if (joinSapStudy.getCode() == 0) {
                return new SimpleJson(1, "你还没有加入学习小组，无法退出");
            }
            String code = getRandomString(4);
            code=code.toUpperCase();
            cacheMap = redisCache.getCacheMap(ConstantUntil.CACHE_SAWBS_QUIT_CODE);
            if (cacheMap != null) {
                if (cacheMap.containsKey(JwtUtil.getUserForToken())) {
                    return new SimpleJson(1, "验证码有效期24小时，请不要重复发送验证码，长时间没有收到邮件，请联系会长");
                }
            } else {
                cacheMap = new HashMap<>(1);
            }
            cacheMap.put(JwtUtil.getUserForToken(), code);
            Map<String,Integer> timeCacheMap = new HashMap<>(1);
            timeCacheMap = redisCache.getCacheMap(ConstantUntil.CACHE_SAWBS_QUIT_CODE_TIME);
            timeCacheMap.put(JwtUtil.getUserForToken(),1);
            redisCache.setCacheMap(ConstantUntil.CACHE_SAWBS_QUIT_CODE, cacheMap);
            redisCache.setCacheMap(ConstantUntil.CACHE_SAWBS_QUIT_CODE_TIME, timeCacheMap);
            String email = EmailUntil.emailForQuitSawbs(JwtUtil.getUserForToken(), cacheService.getRealNameCache(cacheService.getRealNameCacheMap(), JwtUtil.getUserForToken()), new Timestamp(System.currentTimeMillis()).toString(), code);
            UserMessage userMessage = userService.getUserMessage(JwtUtil.getUserForToken());
            imailService.sendHtmlMail(userMessage.getQq() + "@qq.com", "软协小组退出验证码", email);
        } catch (Exception e) {
            e.printStackTrace();
            assert cacheMap != null;
            cacheMap.remove(JwtUtil.getUserForToken());
            redisCache.setCacheMap(ConstantUntil.CACHE_SAWBS_QUIT_CODE, cacheMap);
            return new SimpleJson(1, "邮件发送错误，请联系会长");

        }
        return new SimpleJson(0, "验证码邮件已成功发送，请注意查收");
    }

    @PreAuthorize("hasAuthority('正式成员')")
    @GetMapping("/quitSawbs")
    public SimpleJson quitSawbs(@RequestParam("code") String code) {
        Map<String, Object> cacheMap = redisCache.getCacheMap(ConstantUntil.CACHE_SAWBS_QUIT_CODE);
        if (!cacheMap.containsKey(JwtUtil.getUserForToken())) {
            return new SimpleJson(1, "不存在学号:" + JwtUtil.getUserForToken() + "的验证码");
        }
        String mapCode = (String) cacheMap.get(JwtUtil.getUserForToken());
        if (!Objects.equals(mapCode, code)) {
            return new SimpleJson(1, "验证码错误");
        } else {
            Map<String, Integer> timeCacheMap = redisCache.getCacheMap(ConstantUntil.CACHE_SAWBS_QUIT_CODE_TIME);
            timeCacheMap.remove(JwtUtil.getUserForToken());
            return sawbsService.quitSawbs(new DynamicMessage(dynamicService.getYearForInt(), dynamicService.getOrderForInt(), null, JwtUtil.getUserForToken()));
        }
    }

    @PreAuthorize("hasAuthority('正式成员')")
    @PostMapping("/submitSawbsForWeek")
    public SimpleJson submitSawbsForWeek(HttpServletRequest httpRequest) {
        List<MultipartFile> file = ((MultipartHttpServletRequest) httpRequest).getFiles("file");
        if (file.isEmpty()) {
            return new SimpleJson(1, "请携带文件上传");
        }
        if (file.size() != 1) {
            return new SimpleJson(1, "仅支持一个文件的上传，不允许多个文件上传");
        }
        if (!Objects.requireNonNull(file.get(0).getOriginalFilename()).endsWith(".md")) {
            return new SimpleJson(1, "仅支持.md文件上传");
        }
        return sawbsService.submitSawbsForWeek(new DynamicMessage(dynamicService.getYearForInt(), dynamicService.getOrderForInt(), dynamicService.getWeekForInt(), JwtUtil.getUserForToken()), file.get(0));
    }

    @PreAuthorize("hasAuthority('游客')")
    @GetMapping("/isSubmitForWeek")
    public SimpleJson isSubmitForWeek() {
        return sawbsService.isSubmitForWeek(new DynamicMessage(dynamicService.getYearForInt(), dynamicService.getOrderForInt(), dynamicService.getWeekForInt(), JwtUtil.getUserForToken()));
    }

    /**
     * 通过年，次，周获取用户任务提交的信息
     *
     * @param year   年，必要
     * @param order  次，不必要
     * @param week   周，不必要
     * @param submit 是否提交，1表示提交，2表示没有提交
     * @return 用户任务信息
     */
    @PreAuthorize("hasAuthority('正式成员')")
    @GetMapping("/getTaskInfoByYearOrderWeek")
    public SimpleJson getTaskInfoByYearOrderWeek(@RequestParam(value = "year", required = false) Integer year,
                                                 @RequestParam(value = "order", required = false) Integer order,
                                                 @RequestParam(value = "week", required = false) Integer week,
                                                 @RequestParam(value = "submit", required = false) Integer submit) {
        return sawbsService.getTaskInfoByYearOrderWeek(year, order, week, submit);
    }

    @PreAuthorize("hasAuthority('正式成员')")
    @PostMapping("/updateFileForUserWeek")
    public SimpleJson updateFileForUserWeek(HttpServletRequest request) {
        List<MultipartFile> file = ((MultipartHttpServletRequest) request).getFiles("file");
        SimpleJson submitForWeek = isSubmitForWeek();
        if (submitForWeek.getCode() == 0) {
            return new SimpleJson(1, "在没有上传文件时，无法调用修改文件的接口");
        }
        if (file.size() != 1) {
            return new SimpleJson(1, "仅支持一个文件的上传，不允许多个文件上传");
        }
        return sawbsService.updateSubmitTaskForWeek(new DynamicMessage(dynamicService.getYearForInt(), dynamicService.getOrderForInt(), dynamicService.getWeekForInt(), JwtUtil.getUserForToken()), file.get(0));
    }

    @PreAuthorize("hasAuthority('正式成员')")
    @GetMapping("/getTaskInfoByUsername")
    public SimpleJson getTaskInfoByUsername() {
        return sawbsService.getTaskInfoByUsername();
    }

    @PreAuthorize("hasAuthority('会长')")
    @GetMapping("/sendReminders")
    public SimpleJson sendReminders(){
        try{
            sawbsService.sendReminders();
        }catch (RuntimeException e){
            return new SimpleJson(1,"出现未知错误");
        }
        return new SimpleJson(0,"邮件发送成功，请排查日志看有没有邮件没发送成功的！");
    }
}
